import { LOCAL_STORAGE_KEY } from "@/utils/Constants.js";
import Api from "@/utils/Api.js";

const request = (config) => {
    const {
        url,
        data = {},
        method = 'POST',
        dataType = 'json',
        showLoading = true,
        showError = true,
        timeout = 10000
    } = config;

    const baseUrl = uni.getSystemInfoSync().uniPlatform === "web"
        ? "/api"
        : `${Api.domain}`;

    return new Promise((resolve, reject) => {
        if (showLoading) {
            uni.showLoading({
                title: '加载中...',
                mask: true
            });
        }

        const header = {
            'Content-Type': dataType === 'json'
                ? 'application/json'
                : 'application/x-www-form-urlencoded',
            'token': uni.getStorageSync(LOCAL_STORAGE_KEY.token.key),
        };

        let timeoutTimer = setTimeout(() => {
            requestTask?.abort();
            handleNetworkError();
        }, timeout);

        const handleNetworkError = () => {
            clearTimeout(timeoutTimer);
            if (showLoading) uni.hideLoading();

            uni.redirectTo({
                url: '/pages/error/networkError'
            });

            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/home/HomeIndex'
                });
            }, 3000);

            reject(new Error(`请求超时(${timeout}ms)`));
        };

        const showErrorMessage = (message) => {
            if (showError && message) {
                uni.showToast({
                    title: message,
                    icon: 'none',
                    duration: 2000
                });
            }
        };

        const requestTask = uni.request({
            url: baseUrl + url,
            data,
            header,
            method,
            timeout,
            success: (res) => {
                clearTimeout(timeoutTimer);
                const response = res.data || {};

                // HTTP状态码非200处理
                if (res.statusCode !== 200) {
                    const error = new Error(`[${res.statusCode}] ${res.errMsg || '请求失败'}`);
                    showErrorMessage(response.msg || error.message);
                    reject(error);
                    return;
                }

                // HTTP 200 情况下处理业务逻辑
                try {
                    // 业务成功判断条件（根据AjaxResult规范）
                    const isSuccess = response.code === HttpStatus.SUCCESS;

                    if (!isSuccess) {
                        // 业务错误：显示服务端返回的msg信息
                        const errorMsg = response.msg || '操作失败';
                        showErrorMessage(errorMsg);
                        reject(new Error(errorMsg));
                        return;
                    }

                    // Token过期处理（901状态码）
                    if (response.code === 901) {
                        showErrorMessage('登录状态已过期');
                        uni.removeStorageSync(LOCAL_STORAGE_KEY.token.key);
                        uni.navigateTo({
                            url: '/pages/login/Login',
                            success: () => reject(new Error('登录已过期')),
                            fail: (err) => {
                                console.error('跳转登录页失败:', err);
                                reject(new Error('系统错误'));
                            }
                        });
                        return;
                    }

                    // 成功响应：返回data字段（符合AjaxResult规范）
                    resolve(response.data);
                } catch (e) {
                    showErrorMessage('响应数据解析失败');
                    reject(new Error('响应数据解析失败'));
                }
            },
            fail: (err) => {
                if (err.errMsg.includes("timeout") || err.errMsg.includes("网络")) {
                    handleNetworkError();
                } else {
                    clearTimeout(timeoutTimer);
                    if (showLoading) uni.hideLoading();
                    showErrorMessage('网络连接异常，请检查网络设置');
                    reject(new Error(err.errMsg || '网络错误'));
                }
            },
            complete: () => {
                if (showLoading) uni.hideLoading();
            }
        });
    });
};

// 状态码常量（需与后端AjaxResult保持一致）
const HttpStatus = {
    SUCCESS: 200,  // 成功
    WARN: 601,     // 警告
    ERROR: 500,    // 错误
    TOKEN_EXPIRED: 901 // Token过期
};

export default request;